package com.licoba.emoji.atys;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.androidadvance.topsnackbar.TSnackbar;
import com.licoba.emoji.MainActivity;
import com.licoba.emoji.R;
import com.licoba.emoji.bean.User;
import com.licoba.emoji.databinding.ActivityWelcomeBinding;
import com.licoba.emoji.utils.LiSnackbar;
import com.licoba.emoji.utils.SnackbarUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

/**
 * @site www.licoba.top
 * @date 2018/10/11  9:20
 * @note 登录界面（QQ登录+微信登录，相互独立）
 */
public class WelcomeActivity extends AppCompatActivity {


    public  ActivityWelcomeBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_welcome);
        //隐藏AppCompatActivity自带的ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        //使用QQ登录，wiki：http://wiki.mob.com/%E7%AC%AC%E4%B8%89%E6%96%B9%E7%99%BB%E5%BD%95/
        binding.loginQq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //要数据，不要功能:入口方法是showUser(null)；
                final Platform plat_qq = ShareSDK.getPlatform(QQ.NAME);

                if(!plat_qq.isClientValid()){
                    LiSnackbar.warning(binding.getRoot(),"😕 未检测到QQ客户端");
                    return;
                }

                if (plat_qq.isAuthValid()) {  //如果授权就删除授权资料
                    plat_qq.removeAccount(true);
                }

                plat_qq.setPlatformActionListener(new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Log.e("ShareSDK", "onComplete");

                        PlatformDb platDB = platform.getDb();//获取数平台数据DB
                        String userIcon = platDB.getUserIcon();
                        String userId =  platDB.getUserId();
                        String userName =   platDB.getUserName();
                        System.out.println("登录信息："+userIcon+"： "+userId+":"+userName);



                        final User user = new User();
                        user.setNickname(userName);
                        user.setAvatar(userIcon);
                        user.setPlatform("QQ用户");
                        user.setPlatformId(userId);


                        //查找Person表里面id为6b6c11c537的数据
                        BmobQuery<User> query = new BmobQuery<User>();
                        query.addWhereEqualTo("platformId", userId);
                        query.findObjects(new FindListener<User>() {
                            @Override
                            public void done(List<User> list, BmobException e) {
                                if(e==null){ //查询正常
                                    if(list.size()>0)
                                        oldUser(user);
                                    else
                                       addUser(user);
                                }else{
                                    Log.e("Bmob查询数据","查询数据失败：" + e.getMessage());
                                }
                            }
                        });



//                        WelcomeActivity.this.finish();

                    }

                    //添加新用户
                    public void  addUser(final User user){
                        user.save(new SaveListener<String>() {
                            @Override
                            public void done(String objectId,BmobException e) {
                                if(e==null){
                                    Log.e("Bmob插入数据","添加数据成功，返回objectId为："+objectId);
                                    LiSnackbar.success(binding.getRoot(),"Hello^-^：" + user.getNickname());
                                    final Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
                                    new Handler().postDelayed(new Runnable() {
                                        public void run() {
                                            //你需要跳转的地方的代码
                                            startActivity(intent);
                                        }
                                    }, 1500); //延迟2秒跳转
                                }else{
                                    Log.e("Bmob插入数据","创建数据失败：" + e.getMessage());
                                }
                            }
                        });
                    }

                    //欢迎老用户
                    public void  oldUser(User user){
//                        Log.e("Bmob登录","欢迎回来：" + user.getNickname());
//                        SnackbarUtils.Short(binding.getRoot(),"欢迎回来：" + user.getNickname()).confirm().gravityFrameLayout(Gravity.TOP).show();

                        LiSnackbar.success(binding.getRoot(),"😁 欢迎回来：" + user.getNickname());
                        final Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
//                        startActivity(intent);

                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                //你需要跳转的地方的代码
                                startActivity(intent);
                            }
                        }, 1500); //延迟2秒跳转

                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        LiSnackbar.success(binding.getRoot(),"登录失败：" + throwable.getMessage());
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {

                        Log.e("ShareSDK", "onCancel");
                    }
                });

                plat_qq.showUser(null);

            }

        }); //end onclick


        //使用微信登录
        binding.loginWeixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LiSnackbar.warning(binding.getRoot(),"🙃 微信未开放个人开发者登录授权");
//                Toast.makeText(getApplicationContext(),"由于微信开发者认证需要300rmb，未认证，无法进行微信登录……",Toast.LENGTH_SHORT).show();
                return;
            }
        }); //end onclick


        //使用微博登录
        binding.loginWeibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //要数据，不要功能:入口方法是showUser(null)；
                final Platform plat_weibo = ShareSDK.getPlatform(SinaWeibo.NAME);

                if (plat_weibo.isAuthValid()) {  //如果授权就删除授权资料
                    plat_weibo.removeAccount(true);
                }

                plat_weibo.setPlatformActionListener(new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Log.e("ShareSDK", "onComplete");

                        PlatformDb platDB = platform.getDb();//获取数平台数据DB
                        String userIcon = platDB.getUserIcon();
                        String userId =  platDB.getUserId();
                        String userName =   platDB.getUserName();
                        System.out.println("登录信息："+userIcon+"： "+userId+":"+userName);

                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        Log.e("ShareSDK", "onCancel ---->  登录取消");
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {

                        Log.e("ShareSDK", "onCancel");
                    }
                });

                plat_weibo.showUser(null);
            }
        }); //end onclick


    }
}
